﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.Core.DomainModel;

namespace MethodWorx.Core.DomainModel
{
    /// <summary>
    /// A managed unit of work used to track changes to inner unit of works
    /// that are spawned from outer units of work to contain uncommited changes
    /// </summary>
    public class InnerUnitOfWork : UnitOfWork
    {
        private IUnitOfWork outer;

        public InnerUnitOfWork(IUnitOfWork outer)
        {
            if (outer == null)
                throw new ArgumentNullException("outer");

            this.outer = outer;
        }

        protected override void OnCommit()
        {
            //
            //  ok, here it is our responsibility to map this unit of work into the parent unit of work

            //  we do this by going through our cache
            //  and spitting it into the parent
            foreach (AggregateRoot inserted in this.inserted.Values)
            {
                this.outer.RegisterAdded(inserted);
            }

            foreach (AggregateRoot updated in this.updated.Values)
            {
                this.outer.RegisterChanged(updated);
            }

            foreach (AggregateRoot deleted in this.deleted.Values)
            {
                this.outer.RegisterDeleted(deleted);
            }
        }

        protected override void OnCancel()
        {
        }
    }
}
